const { goodsFormatError, invalidGoodsID } = require('../constant/err.type')
const { findOne } = require('../service/goods.service')


// 参数校验
const paramValidator = async (ctx, next) => {
    try {
        ctx.verifyParams({
            goods_name: { type: "string", require: true },
            goods_price: { type: "number", require: true },
            goods_num: { type: "number", require: true },
            goods_img: { type: "string", require: true }
        })
    } catch (error) {
        // 错误处理
        console.error(error)
        goodsFormatError.result = error
        return ctx.app.emit('error', goodsFormatError, ctx)
    }
    await next()
}
// 商品 是否存在
const verifyGoods = async (ctx, next) => {
    const { goods_id } = ctx.request.body
    try {
        const res = await findOne(goods_id)
        if (!res) {
            console.error('无效的商品ID', { goods_id })
            ctx.app.emit('error', invalidGoodsID, ctx)
            return
        }
    } catch (err) {
        console.error('获取信息错误!', err)
        ctx.app.emit('error', invalidGoodsID, ctx)
        return
    }
    await next()
}
module.exports = {
    paramValidator, verifyGoods
}